import time
from params_encSecKey import *


class playlist_get_allSong(object):
    def get_allID(self, playlist_id):
        time.sleep(1)
        playlist_api = 'https://music.163.com/weapi/v6/playlist/detail?'
        data = {
            'csrf_token': "",
            'id': str(playlist_id),
            'n': "0"
        }
        wyy_params = Netease_params(data)
        response = wyy_params.run(playlist_api)['playlist']
        # print(response)
        playlist_info = dict()
        playlist_info['id'] = response['id']
        playlist_info['name'] = response['name']
        playlist_info['description'] = response['description']
        id_list = [i['id'] for i in response['trackIds']]
        playlist_info['c'] = [{'id': i} for i in id_list]

        ''' 效果等同于上句
            playlist_info['c'] = []
            for i in id_list:
                info = {'id':i}
                playlist_info['c'].append(info)
        '''
        # print(playlist_info)
        return playlist_info

    def get_song_info(self, c):
        time.sleep(1)
        song_api = 'https://music.163.com/weapi/v3/song/detail'
        data = {
            'c': str(c),
            'csrf_token': ''
        }
        wyy_params = Netease_params(data)
        song_info = wyy_params.run(song_api)['songs']
        # print(song_info)
        return song_info

    def save_text(self, playlist_info, song_info):
        name = playlist_info['name']

        intab = "?*/\|.:><"
        outtab = "         "
        trantab = str.maketrans(intab, outtab)
        name = name.translate(trantab)

        text_path = f"./{name}.txt"

        short_info = {}

        for count in range(len(song_info)):
            info = song_info[count]
            artist_list = [i['name'] for i in info['ar']]
            song_url = f"https://music.163.com/#/song?id={info['id']}"

            update_dic = {info['name']: song_url}
            # print(update_dic)
            short_info.update(update_dic)

            with open(text_path, 'a+', encoding='utf8') as fp:
                fp.write(f"{count+1}《{','.join(artist_list)} - {info['name']}》\n{song_url}\n\n")

        # 格式化json输出
        # with open(text_path, 'a+', encoding='utf8') as fp:
        #     fp.write(str(short_info))

    def run(self, playlist_id):
        print("获取歌单信息")
        playlist_info = self.get_allID(playlist_id)

        print("获取歌曲信息")
        song_info = self.get_song_info(playlist_info['c'])
        print(song_info)

        print("保存文件中")
        self.save_text(playlist_info, song_info)

        print("done")


if __name__ == "__main__":
    # https://music.163.com/#/playlist?id=6918992424
    # https://music.163.com/playlist?id=7990661746&userid=357301093
    playlist_id = 9127278592
    allSong = playlist_get_allSong()
    allSong.run(playlist_id)
